package com.cssy.yd.logic.web;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.logic.entity.LogicMaterialReturnDO;
import com.cssy.yd.logic.entity.LogicMaterialReturnItemBatchDO;
import com.cssy.yd.logic.entity.LogicMaterialReturnItemDO;
import com.cssy.yd.logic.service.ILogicMaterialReturnItemBatchService;
import com.cssy.yd.logic.service.ILogicMaterialReturnItemService;
import com.cssy.yd.logic.service.ILogicMaterialReturnService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;

@Controller
@RequestMapping("/yd/logic/materialreturn")
public class LogicMaterialReturnController extends BaseController<LogicMaterialReturnDO>{

	private static final String MANAGER = "/yd/logic/materialreturn/MaReturnManager";
	private static final String EIDT = "/yd/logic/materialreturn/MaReturnOperation";//添加、修改、显示页面
	private static final String ITEMMANAGER = "/yd/logic/materialreturn/MaReturnItemManager";//添加、修改、显示页面
	@Resource(name = "logicMaterialReturnService")
	private ILogicMaterialReturnService logicMaterialReturnService;
	
	@Resource(name = "logicMaterialReturnItemService")
	private ILogicMaterialReturnItemService logicMaterialReturnItemService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name="logicMaterialReturnItemBatchService")
	private ILogicMaterialReturnItemBatchService logicMaterialReturnItemBatchService;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}

	@RequestMapping(value="itemManager")
	public String itemManager(HttpServletRequest request, Model model)
			throws Exception {
		String itemdata =request.getParameter("data");
		String billstatus =request.getParameter("billstatus");
		LogicMaterialReturnItemDO lReturnItemDO=JSONArray.parseObject(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"), LogicMaterialReturnItemDO.class);
		LogicMaterialReturnItemBatchDO mItemBatchDO = new LogicMaterialReturnItemBatchDO();
		mItemBatchDO.setMaterialsid(lReturnItemDO.getMaterialsid());
		mItemBatchDO.setMareturnitemid(lReturnItemDO.getId());
		mItemBatchDO.setCode(lReturnItemDO.getCode());
		mItemBatchDO.setName(lReturnItemDO.getName());
		mItemBatchDO.setSpec(lReturnItemDO.getSpec());
		mItemBatchDO.setJunit(lReturnItemDO.getJunit());
		mItemBatchDO.setUnit(lReturnItemDO.getUnit());
		mItemBatchDO.setUnitconvert(lReturnItemDO.getUnitconvert());
		
		if(lReturnItemDO.getItemBatch() != null & !"".equals(lReturnItemDO.getItemBatch())){
			request.setAttribute("itemBatchDOs", lReturnItemDO.getItemBatch());
		}
		
		request.setAttribute("billstatus", billstatus);
		request.setAttribute("mItemBatchDO", JSONArray.toJSONString(mItemBatchDO));
		return ITEMMANAGER;
	}
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		Map<String,Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService, "whcode");
		scs.addCondition((String)sqlMap.get("option"), (List)sqlMap.get("roleWhList"));
		hander.getWheres(scs);
			if(scs.getOrderBy()==null||"".equals(scs.getOrderBy()))
				scs.setOrderBy("dctime desc");
		SearchResult result= logicMaterialReturnService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}
	@RequestMapping(value = "/itemlist")
	public void itemlist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String itembatch =request.getParameter("itembatch");
		List<LogicMaterialReturnItemBatchDO> itemBatchDOs=null;
		if(itembatch != null  && !"".equals(itembatch)){
			itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicMaterialReturnItemBatchDO.class);
		}
		SearchResult result= new SearchResult();
//		String mareturnitemid =request.getParameter("mareturnitemid");
//		String code =request.getParameter("code");
//		JqGridHandler hander=new JqGridHandler(request);
//		 SearchConditions scs = new SearchConditions();
//		 hander.getWheres(scs);
//		 scs.setRemovedProperty(null);
//		 List<LogicMaterialReturnItemBatchDO>list= new ArrayList<LogicMaterialReturnItemBatchDO>();
//		 if((!"".equals(mareturnitemid) && mareturnitemid != null) && (!"".equals(code) && code != null)){
//			 scs.addCondition("mareturnitemid", mareturnitemid, SearchCondition.OP_EQUAL);
//			 scs.addCondition("code", code, SearchCondition.OP_EQUAL);
//			 list= logicPoReturnItemBatchService.findListByExample(scs).getResults();
//		 }
//		 if(itemBatchDOs != null){
//			 for (LogicMaterialReturnItemBatchDO returnItemBatchDO : itemBatchDOs) {
//					if(returnItemBatchDO.getId() == null){
//						list.add(returnItemBatchDO);
//					}
//				}
//		 }
		if(itemBatchDOs !=null){
			result.setRecordCount(itemBatchDOs.size());
			result.setResults(itemBatchDOs);
		}
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);
		
	}
	@Override
	public String operationForm(HttpServletRequest request,@PathVariable String id,
			@PathVariable  String flag, Model model) throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("viewflag", "add");
			model.addAttribute("xx", 1);//标示能不能修改内容
		}else{
			LogicMaterialReturnDO mrDO = logicMaterialReturnService.findListById(id);
			//List<LogicMaterialReturnItemDO> lmrilist = logicMaterialReturnItemService.findByMaReturnid(id);
			if (mrDO.getBillStatus() == 1){
				model.addAttribute("xx", 1);//标示能不能修改内容
				model.addAttribute("viewflag", "tijiao");
			}else {
				model.addAttribute("xx", 2);//标示能不能修改内容
			}
			if (mrDO.getBillStatus() == 3){
				model.addAttribute("viewflag", "tongguo");
			}
			if (mrDO.getBillStatus() == 2){
				model.addAttribute("viewflag", "shenpi");
			}
			model.addAttribute("mrDO", mrDO);
			//model.addAttribute("axxJson", lmrilist);
			
		}
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			List<LogicMaterialReturnItemDO> lmrilist = logicMaterialReturnItemService.findByMaReturnid(id);
			OutJsonGrid out = new OutJsonGrid(lmrilist);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicMaterialReturnDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata = request.getParameter("addressInfos");
		//String type=request.getParameter("type");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("物料不能为空！");
			return bodyMap.modelMap;
		}else{
				List<LogicMaterialReturnItemDO> lReturnItemDOs  = JSONArray.parseArray(itemdata, LogicMaterialReturnItemDO.class);
				for (LogicMaterialReturnItemDO itemDO : lReturnItemDOs) {
					if("Y".equals(itemDO.getOpenBatch())){
						if("".equals(itemDO.getItemBatch()) || itemDO.getItemBatch()==null){
							bodyMap.isFail();
							bodyMap.configWebInfor("物料编码为:'"+itemDO.getCode()+"'没有分批次填写数据！");
							return bodyMap.modelMap;
						}else{
							List<LogicMaterialReturnItemBatchDO> batchDOs  = JSONArray.parseArray(itemDO.getItemBatch(), LogicMaterialReturnItemBatchDO.class);
							if(batchDOs==null || batchDOs.size() <= 0){
								bodyMap.isFail();
								bodyMap.configWebInfor("物料编码为:'"+itemDO.getCode()+"'没有分批次填写数据！");
								return bodyMap.modelMap;
							}
						}
					}
				}
			
		}
		try {
			/*if(!StringUtil.valitate(curAP.getBatch())&&!StringUtil.valitate(curAP.getId())){
				bodyMap.isFail();
				bodyMap.configWebInfor("退料入库的批次不能为空！");
				return bodyMap.modelMap;
			}else{
				if(curAP.getBillStatus()!=3){
					if(curAP.getBatch()!=null){
						curAP.setBatch("TL"+curAP.getBatch().replace("TL", ""));
					}
					SearchConditions scs = new SearchConditions();
					 if(StringUtil.valitate(curAP.getId())){
						 scs.addCondition("id",curAP.getId(),SearchCondition.OP_NOTEQUAL);
					 }
					 scs.addCondition("batch",curAP.getBatch(),SearchCondition.OP_EQUAL);
					 SearchResult sr= logicMaterialReturnService.findListByExample(scs);
					 if(sr.getResults().size()>0){
							bodyMap.isFail();
							bodyMap.configWebInfor("您填写的批次已存在，请重新填写");
							return bodyMap.modelMap;
					}
				}
			}*/
			logicMaterialReturnService.tlSave(curAP, request);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (SyBaseException e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap=BodyMsg.getInstance();
		try{
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicMaterialReturnDO lmr=logicMaterialReturnService.findListById(field);
				if(lmr.getId()!=null){
					lmr.setRemoved(1);
					logicMaterialReturnService.update(lmr, SessionUtil.getUser(request));
				}
			}
		
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@RequestMapping(value = "/updateState")
	@ResponseBody
	public Map<String,String> updateState(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String,String> map=new HashMap<String, String>();
		try{
			String ids = request.getParameter("rows");
			if(ids!=null&&!"".equals(ids)){
				LogicMaterialReturnDO lmr=logicMaterialReturnService.findListById(ids);
				if(lmr.getId()!=null){
					lmr.setBillStatus(1);
					logicMaterialReturnService.update(lmr, SessionUtil.getUser(request));
					map.put("msg", "SUCCESS");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		return map;
	}
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
		try {
				String id = request.getParameter("id");
				LogicMaterialReturnDO mr=new LogicMaterialReturnDO();
				List<LogicMaterialReturnItemDO> itemlist=new ArrayList<LogicMaterialReturnItemDO>();
				List<LogicMaterialReturnItemBatchDO> itemBatchDOs=new ArrayList<LogicMaterialReturnItemBatchDO>();
				if(!"".equals(id)&&id!=null){
					mr =logicMaterialReturnService.findListById(id);
				}
				if(mr.getId()!=null){
					SearchConditions scs = new SearchConditions();
					scs.addCondition("mareturnid", mr.getId(),SearchCondition.OP_EQUAL);
					scs.setLimitPage(false);
					scs.setRemovedProperty(null);
					scs.setOrderBy("code asc");
					itemlist =logicMaterialReturnItemService.findListByExample(scs).getResults();
					if(itemlist!=null){
						int k = 1;
						for (LogicMaterialReturnItemDO lmr : itemlist) {
							SearchConditions scs2 = new SearchConditions();
							scs2.addCondition("mareturnItemid", lmr.getId(),SearchCondition.OP_EQUAL);
							scs2.setLimitPage(false);
							scs2.setRemovedProperty(null);
							scs2.setOrderBy("code asc");
							List<LogicMaterialReturnItemBatchDO> list = logicMaterialReturnItemBatchService.findListByExample(scs2).getResults();
							if(list!=null){
								for (LogicMaterialReturnItemBatchDO mrItemBatch : list) {
									mrItemBatch.setId(k+"");
									if(mrItemBatch.getName()!=null && mrItemBatch.getSpec()!=null){
										mrItemBatch.setSpec(";"+mrItemBatch.getSpec());
									}else{
										mrItemBatch.setSpec(mrItemBatch.getSpec());
									}
									mrItemBatch.setHubname(mr.getWhCode());
									itemBatchDOs.add(mrItemBatch);
									k++;
								}
							}
							
						}
						for (LogicMaterialReturnItemDO lmrItemDO : itemlist) {
							LogicMaterialReturnItemBatchDO batch = new LogicMaterialReturnItemBatchDO();
							if(!"Y".equals(lmrItemDO.getOpenBatch())){
								batch.setId(k+"");
								batch.setName(lmrItemDO.getName());
								if(lmrItemDO.getName()!=null && lmrItemDO.getSpec()!=null){
									batch.setSpec(";"+lmrItemDO.getSpec());
								}else{
									batch.setSpec(lmrItemDO.getSpec());
								}
								batch.setCode(lmrItemDO.getCode());
								batch.setHubname(mr.getWhCode());
								batch.setSpec(lmrItemDO.getSpec());
								batch.setJunit(lmrItemDO.getJunit());
								batch.setJquantity(lmrItemDO.getJquantity());
								itemBatchDOs.add(batch);
								k++;
							}
						}
					}
				}
				if(itemBatchDOs.size()<11){
					int s = 8-itemBatchDOs.size();
					int n =itemBatchDOs.size();
					for (int i = 0; i < s; i++) {
						LogicMaterialReturnItemBatchDO item = new LogicMaterialReturnItemBatchDO();
						item.setId(n+1+i+"");
						itemBatchDOs.add(item);
					}
				}
				request.setCharacterEncoding("utf-8");
				response.setContentType("application/vnd.ms-excel;charset=utf-8"); 
//				String fileNameDisplay = "采购入库单";
//				try {
//					fileNameDisplay = new String(fileNameDisplay.getBytes("GBK"),
//							"iso-8859-1");
//				} catch (UnsupportedEncodingException e1) {
//					e1.printStackTrace();
//				}
				response.setHeader("Content-disposition", "attachment;filename="+mr.getMareturnCode()+".xls");
				OutputStream os= response.getOutputStream(); 
		//		Map<String,Object> pMap = request.getParameterMap();
		//		List<Map> data = new ArrayList<Map>();
				XLSTransformer transformer = new XLSTransformer();
			    StringBuffer file=new StringBuffer(request.getRealPath("/"));;
				file.append("/views/printer/excelTemplate/materialreturn.xls");
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("mr", mr);
				map.put("item", itemBatchDOs);
				Workbook book= transformer.transformXLS(new FileInputStream(file.toString()), map);    						
					book.write(os);				
					os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
